from flask import Flask
from flask import request,session
from flask import render_template

#试验6，指定了静态文件夹后，样式出现
app =Flask(__name__,static_url_path='',static_folder='templates/static')
app.secret_key='123456'

@app.route("/getuser")
def getuser():
    if 'username' in session:
        print('hello, {}\n'.format(session['username']))
    return render_template('loginok.html')

@app.route("/login",methods=['POST'])
def dologin():
    session['username']=request.form['username']
    # sessionId=request.cookies.get('session')
    return render_template('loginok.html')

@app.route("/logout")
def dologout():
    if session.__contains__('username'):
        session.pop('username')
    return render_template('login.html')

#路由指定路径对应的处理代码
@app.route('/')
@app.route('/index.html')
def hello_world():
    return 'Hello world'


@app.route('/reg')
def reg_forward():
    return render_template('register.html')

@app.route('/reg_get')
def reg_get():
    print("返回请求类型",request.method)

    if request.method == "GET":
        username=request.args.get('name')
        pwd=request.args.get('pwd')
        print('收到注册内容用户名{0}，密码{1}'.format(username,pwd))

    return "注册成功"

@app.route('/reg_post',methods=['POST'])
def reg_post():
    print('post请求')
    #get 请求用的是args post用的是form
    username=request.form.get('name')
    pwd=request.form.get('pwd')
    print('收到注册内容用户名{0}，密码{1}'.format(username,pwd))

    return 'post ok'
#渲染
#需要引入
#from flask import render_template
@app.route("/hellorender")
@app.route("/hellorender/<name>")
def hello(name=None):
    return render_template('index.html',name=name)



#rest 风格？
@app.route("/user/<username>")
def sayHello(username):
    return '你好'+username

@app.route("/user/<int:uid>")
def sayHello2(uid):
    return '编号为{}的用户'.format(uid)


# @app.route("/user/<username>-<int:uid>")
# def sayHello3(username,uid):
#     return "您好编号{0}的用户：{1}".format(uid,username)

@app.route("/user/<username>/<int:uid>")
def sayHello3(username,uid):
    return "您好编号{0}的用户：{1}".format(uid,username)


@app.route("/methodt",methods=['GET','POST'])
def methodt():
    #request 需要引入 from flask import request
    if request.method =='POST':
        return dopost()
    else:
        return doget()


def doget():
    return '''
     Get 访问
     <form action='methodt'  method='post'>
        <input value="post" type="submit"/>
     </form>
    '''

def dopost():
    return "post 访问"
#启动服务器
if __name__=='__main__':
    #调试模式
    app.debug=True
    app.run(host="0.0.0.0",port=80)

# 感觉像node ,自带服务器，
# 代码像sprint mvc和struts2